package internal

import (
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"

	"time"
)

var DB *gorm.DB
var err error

func InitDB() {
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	//dsn := "root:yaochizaocan@tcp(192.168.75.10:3306)/practice01?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		AppConf.DBConfig.UserName,
		AppConf.DBConfig.Password,
		AppConf.DBConfig.Host,
		AppConf.DBConfig.Port,
		AppConf.DBConfig.DBName,
	)
	zap.S().Info(dsn)
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold:             time.Second, // 慢 SQL 阈值
			LogLevel:                  logger.Info, // 日志级别
			IgnoreRecordNotFoundError: true,        // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  true,        // 禁用彩色打印
		},
	)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
		NamingStrategy: schema.NamingStrategy{
			//TablePrefix:   "pra01_", //表名前缀
			SingularTable: true, //是否使用复数进行命名
		},
	})
	if err != nil {
		panic("数据库连接失败.") //当数据库连接不上的时候可以直接panic进行报错
	}
	fmt.Println("连接成功")

	//err = DB.AutoMigrate(&model.ShopCart{}, &model.OrderItem{}, &model.OrderProduct{})
	//if err != nil {
	//	zap.S().Error(err)
	//	panic(err)
	//}
}

func MyPaging(pageNO, pageSize int32) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if pageNO < 1 {
			pageNO = 1
		}
		switch {
		case pageSize < 1:
			pageSize = 10
		case pageSize > 100:
			pageSize = 100
		}
		offset := (pageNO - 1) * pageSize
		MyDB := db.Offset(int(offset)).Limit(int(pageSize)) //注意这里使用的db是传入后的db而不是全局的DB.
		return MyDB

	}
}
